/**
 * Source file: IDValidation.ejs
 * Copyright (C) 2013 : Quantum Solutions
 * Id: $Id: Function_IDValidation.ejs 85 2013-04-21 22:35:52Z WillieVisagie55@gmail.com $
 * Date: $Date: 2013-04-22 00:35:52 +0200 (Mon, 22 Apr 2013) $
 */
function adddouble(number){
	if (number>9) {
		num1 = parseInt((number/10));
		num2 = parseFloat((number/10) - num1);
		num2 = parseInt(Math.round(num2*10));

		number = num1 + num2;
	}
	return number;
}

//If Stillborn, validate the first six digits in date format YYMMDD and the date is not more than 9 months before current date and the last five digits will be zeros
function IDNoValidaterStillBorn(idno) {
	
	if (idno.length != 13 & idno.substring(6, 13) != "0000000") {
		alert ("Format incorrect, should be YYMMDD0000000");
		return false;
	}
	
	if (!CheckDate(idno.substring(4, 6)+idno.substring(2, 4)+"20"+idno.substring(0, 2),false)) {
		//check date displays errors
		return false;
	}

    var iDay = parseInt(idno.substring(4, 6));
    var iMonth = parseInt(idno.substring(2, 4));
    var iYear = parseInt("20"+idno.substring(0, 2));

	
    var pCheckDateDate = new Date(iYear,iMonth -1,iDay);
    var mark = new Date();
	mark.setTime(mark.getTime() - (9 * 30 * 24 * 60 * 60 * 1000));	
	
    if (pCheckDateDate <  mark){
		alert("Still born date cannot be more than 9 months in the past, must be after: "+mark.getFullYear()+"/"+(mark.getMonth()+1)+"/"+mark.getDate());
		return false;
    }
		
	return true;
}

function IDNoValidater(pIdNo) {
	idno = pIdNo.split('');
	
	if (idno.length != 13){
		//alert('idnumber should be 13 digits long, but is '+idno.length);
		return false;
	}
	
	if (!CheckDate(pIdNo.substring(4, 6)+pIdNo.substring(2, 4)+"19"+pIdNo.substring(0, 2),false,1899)) {
		//alert('invalid birth date');
		return false;
	}	
	
	var level1 = 0;
	for (x=0;x<=12;x++) {
		if ((x/2)!=parseInt((x/2))) {
			iddigit = idno[x]*2;
			level1 = level1 + adddouble(iddigit);
		}
	}
	var level2 = 0;
	for (x=0;x<=11;x++){
		if ((x/2)==parseInt((x/2))) {
			iddigit = parseInt(idno[x]);
			level2 = level2 + iddigit;
		}
	}

	leveltotal = level1 + level2;
	remainder = leveltotal - (Math.round(leveltotal/10)*10);
	lastdigit = 10 - remainder;

	if (lastdigit>=10) {
		lastdigit = lastdigit - 10;
	}
	valid = (lastdigit==idno[12]);
	/*
	if (!valid)
		alert('lastdigit should be: ' +lastdigit + ' but it is currently='+ idno[12]);
	else
		alert(idno+' is a valid rsa idnum');
	*/
	return valid;
}


